package cn.xyy.security;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.xyy.common.domain.mvc.R;
import cn.xyy.common.exception.AccessDeniedException;
import cn.xyy.common.utils.LoggerUtil;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 * 
 * @author xyy
 *
 */
@RestControllerAdvice
class GlobalExceptionHandler {

	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public R handleGlobalException(Exception e) {
		LoggerUtil.error("全局异常信息 ex={}", e.getMessage(), e);
		return R.error(e.getLocalizedMessage());
	}

	@ExceptionHandler(AccessDeniedException.class)
	@ResponseStatus(HttpStatus.FORBIDDEN)
	public R handleAccessDeniedException(AccessDeniedException e) {
		LoggerUtil.warn("拒绝请求信息 ex={}", e.getMessage(), e);
		return R.error(e.getLocalizedMessage());
	}

	@ExceptionHandler(NotLoginException.class)
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public R handleNotLoginException(NotLoginException e) {
		LoggerUtil.warn("用户未登录 ex={}", e.getMessage(), e);
		return R.error(401, e.getLocalizedMessage());
	}

	@ExceptionHandler(NotPermissionException.class)
	@ResponseStatus(HttpStatus.FORBIDDEN)
	public R handleNotPermissionException(NotPermissionException e) {
		LoggerUtil.warn("用户没有权限 ex={}", e.getMessage(), e);
		return R.error(e.getLocalizedMessage());
	}

}